package com.genesis.yunnanji.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;
import android.widget.Toast;

import org.xutils.x;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.activity.GoodsDetailsActivity;
import com.genesis.yunnanji.activity.WebActivity;
import com.genesis.yunnanji.adapter.CategoryAdapter;
import com.genesis.yunnanji.adapter.CategoryRightAdapter;
import com.genesis.yunnanji.bean.SpecialtyBannerBean;
import com.genesis.yunnanji.bean.SpecialtyFragmentBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.utils.NetWorkUtils;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration;

import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;

import java.util.ArrayList;
import java.util.List;


/**
 * 创建日期：2018/10/17 001714:10
 * 作者：Kite
 * 描述：
 */
public class SpecialtyFragment extends Fragment {

    private View view;

    private int cate;

    private int page = 1;

    private String connectUrl;//接口连接

    private Banner specialityBanner;

    private RecyclerView rvLeft;

    private RecyclerView rvRight;

    private TwinklingRefreshLayout refreshLayout;

    private CategoryAdapter mCategoryAdapter;//左边适配器

    private CategoryRightAdapter mCategoryRightAdapter;//右边适配器

    private List<SpecialtyBannerBean.ResultBean.ListBean> bannerList = new ArrayList<>();//后台返回banner图

    private List<SpecialtyFragmentBean.ResultBean.ListBean> mLeftBeanList = new ArrayList<>();//后台返回左边的集合

    private List<SpecialtyFragmentBean.ResultBean.ListBean> mLeftTitleList = new ArrayList<>();//获取标题数据集合

    private List<SpecialtyFragmentBean.ResultBean.ListBean.DataBean> mRightDateList = new ArrayList<>();//右边的集合

    public static SpecialtyFragment newInstance(int param) {
        SpecialtyFragment obj = new SpecialtyFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("args1", param);
        obj.setArguments(bundle);
        return obj;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_speciality, null);
            specialityBanner = view.findViewById(R.id.specialty_banner);
            rvLeft = view.findViewById(R.id.rv_left);
            rvRight = view.findViewById(R.id.rv_right);
            //refreshLayout = view.findViewById(R.id.swipe_mushroom_refresh);
            if (getArguments() != null) {
                cate = getArguments().getInt("args1");
                if (cate == 1) {
                    connectUrl = GenesisApiConfig.TECHAN;
                } else if (cate == 2) {
                    connectUrl = GenesisApiConfig.JUNKUN;
                } else if (cate == 3) {
                    connectUrl = GenesisApiConfig.FEIYI;
                }
            }
            netBanner();//加载banner
            getNetDate(refreshLayout);//加载列表
        }
        return view;
    }

    private void getNetDate(final TwinklingRefreshLayout refreshLayout) {
        final RequestParams params = new RequestParams(GenesisApiConfig.HOST + connectUrl);
        params.addBodyParameter("p", page + "");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Gson gson = new Gson();
                SpecialtyFragmentBean bean = gson.fromJson(jsonObject.toString(), SpecialtyFragmentBean.class);
                mLeftBeanList = bean.getResult().getList();

                rvLeft.setLayoutManager(new LinearLayoutManager(getActivity()));
                rvLeft.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.divider)).build());
                mCategoryAdapter = new CategoryAdapter(getActivity(), rvLeft, mLeftTitleList);
                rvLeft.setAdapter(mCategoryAdapter);

                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
                gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int i) {
                        if (mCategoryRightAdapter.getData().get(i).getItemType() == 1 ||
                                mCategoryRightAdapter.getData().get(i).getItemType() == 2) {
                            return 2;
                        } else {
                            return 1;
                        }
                    }
                });
                rvRight.setLayoutManager(gridLayoutManager);
                rvRight.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).size((int) getResources().getDimension(R.dimen.x20)).color(Color.parseColor("#FFFFFF")).build());
                rvRight.addItemDecoration(new VerticalDividerItemDecoration.Builder(getActivity()).size((int) getResources().getDimension(R.dimen.x20)).color(Color.parseColor("#FFFFFF")).build());
                mCategoryRightAdapter = new CategoryRightAdapter(getActivity(), rvRight, mRightDateList);
                rvRight.setAdapter(mCategoryRightAdapter);

                initEvent();
                initDate();
            }

            @Override
            public void OnCached(JSONObject jsonObject) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    private void initBanner() {
        if (bannerList.size() <= 0 || bannerList == null) {
            specialityBanner.setVisibility(View.GONE);
        } else {
            specialityBanner.setVisibility(View.VISIBLE);
            List<String> bannerImages = new ArrayList<>();
            for (int i = 0; i < bannerList.size(); i++) {
                bannerImages.add(bannerList.get(i).getAdvert_img());
            }
            specialityBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            specialityBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    ImageOptions imageOptions = new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.FIT_XY).build();
                    x.image().bind(imageView, GenesisApiConfig.PIC_HOST + (String) path, imageOptions);
                }
            });
            specialityBanner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (bannerList.get(position).getTarget_link().equals("")) {
                        Toast.makeText(getActivity(), "网络链接走丢了!", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(getActivity(), WebActivity.class);
                        intent.putExtra("url", bannerList.get(position).getTarget_link());
                        startActivity(intent);
                    }
                }
            });
            specialityBanner.setIndicatorGravity(BannerConfig.CENTER);
            specialityBanner.isAutoPlay(true);
            specialityBanner.setDelayTime(5000);
            specialityBanner.setImages(bannerImages);
            specialityBanner.start();
        }
    }

    private void netBanner() {
        final RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.BANNER_ADD);
        if (cate == 1) {
            params.addBodyParameter("code", "app_techan_banner");
        } else if (cate == 2) {
            params.addBodyParameter("code", "app_jun_banner");
        } else if (cate == 3) {
            params.addBodyParameter("code", "app_feiyi_banner");
        }
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Gson gson = new Gson();
                SpecialtyBannerBean bean = gson.fromJson(jsonObject.toString(), SpecialtyBannerBean.class);
                bannerList = bean.getResult().getList();
                initBanner();
            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onError(String errorStr) {
            }
        });
    }

    private void initDate() {
        for (int i = 0; i < mLeftBeanList.size(); i++) {
            SpecialtyFragmentBean.ResultBean.ListBean firstBean = new SpecialtyFragmentBean.ResultBean.ListBean();
            firstBean.setTitle(mLeftBeanList.get(i).getTitle());
            firstBean.setGroupId(i);
            mLeftTitleList.add(firstBean);
        }

        mCategoryAdapter.notifyDataSetChanged();

        for (int i = 0; i < mLeftBeanList.size(); i++) {
            SpecialtyFragmentBean.ResultBean.ListBean.DataBean secondBean = new SpecialtyFragmentBean.ResultBean.ListBean.DataBean();
            secondBean.setGroupId(true);
            secondBean.setGroup(i);
            secondBean.setTitle(mLeftBeanList.get(i).getTitle());
            secondBean.setItemType(1);
            mRightDateList.add(secondBean);
            for (int j = 0; j < mLeftBeanList.get(i).getData().size(); j++) {
                SpecialtyFragmentBean.ResultBean.ListBean.DataBean bean = new SpecialtyFragmentBean.ResultBean.ListBean.DataBean();
                bean.setGroup(i);
                bean.setTitle(mLeftBeanList.get(i).getData().get(j).getTitle());
                if (i == 0 && j == 0) {
                    bean.setItemType(2);
                    bean.setId(mLeftBeanList.get(i).getData().get(j).getId());
                    bean.setCover_img(mLeftBeanList.get(i).getData().get(j).getCover_img());
                } else {
                    bean.setItemType(0);
                    bean.setId(mLeftBeanList.get(i).getData().get(j).getId());
                    bean.setCover_img(mLeftBeanList.get(i).getData().get(j).getCover_img());
                }
                mRightDateList.add(bean);
            }
        }

        mCategoryRightAdapter.notifyDataSetChanged();

        mCategoryAdapter.updateCheck(0);
    }

    private int firstVisibleItemPosition = -1;
    private int lastVisibleItemPosition = -1;


    private void initEvent() {
        rvRight.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItemPosition = ((LinearLayoutManager) rvRight.getLayoutManager()).findFirstVisibleItemPosition();
                lastVisibleItemPosition = ((LinearLayoutManager) rvRight.getLayoutManager()).findLastVisibleItemPosition();

                if (mCategoryRightAdapter.isMove()) {//第二次滚动
                    //在这里进行第二次滚动
                    //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                    int n = mCategoryRightAdapter.getIndex() - firstVisibleItemPosition;
                    if (0 <= n && n < rvRight.getChildCount()) {
                        //获取要置顶的项顶部离RecyclerView顶部的距离
                        int top = rvRight.getChildAt(n).getTop();
                        //最后的移动
                        rvRight.scrollBy(0, top);
                    }
                    mCategoryRightAdapter.setMove(false);
                } else {//手动滚动
                    if (dy > 0) {//上滑
                        if (mCategoryRightAdapter.getData().get(firstVisibleItemPosition).getGroup() !=
                                mCategoryAdapter.getData().get(mCategoryAdapter.getCheckedItem()).getGroupId()) {
                            mCategoryAdapter.updateCheck(mCategoryRightAdapter.getData().get(firstVisibleItemPosition).getGroup());
                        }
                    } else if (dy < 0) {//下滑
                        if (mCategoryRightAdapter.getData().get(firstVisibleItemPosition).getGroup() !=
                                mCategoryAdapter.getData().get(mCategoryAdapter.getCheckedItem()).getGroupId()) {
                            mCategoryAdapter.updateCheck(mCategoryRightAdapter.getData().get(firstVisibleItemPosition).getGroup());
                        }
                    }
                }
            }
        });

        mCategoryAdapter.setOnItemClickListener(new CategoryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mCategoryRightAdapter.updatePosition(mCategoryAdapter.getData().get(position).getGroupId());
            }
        });

        mCategoryRightAdapter.setOnItemClickListener(new CategoryRightAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("id", mRightDateList.get(position).getId());
                intent.putExtra("case", cate + "");
                intent.putExtra("title", mRightDateList.get(position).getTitle());
                intent.putExtra("img",mRightDateList.get(position).getCover_img());
                startActivity(intent);
            }
        });

    }

}

